package com.metaverse.backend.web;

import com.metaverse.backend.config.Constants;
import com.metaverse.backend.domain.SysConfig;
import com.metaverse.backend.dto.PageQuery;
import com.metaverse.backend.exception.BusinessException;
import com.metaverse.backend.repo.SysConfigRepo;
import com.metaverse.backend.service.SysConfigService;
import com.metaverse.backend.utils.excel.ExcelUtils;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/sysConfig")
@AllArgsConstructor
public class SysConfigController extends BaseController {
    private SysConfigService sysConfigService;
    private SysConfigRepo sysConfigRepo;

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/save")
    @CacheEvict(value = {Constants.SYS_CONFIG_CACHE}, allEntries = true)
    public SysConfig save(@RequestBody SysConfig record) {
        return sysConfigRepo.save(record);
    }


    @PostMapping("/all")
    public Page<SysConfig> all(@RequestBody PageQuery pageQuery) {
        return sysConfigService.all(pageQuery);
    }

    @GetMapping("/get/{id}")
    public SysConfig get(@PathVariable String id) {
        return sysConfigRepo.findByName(id).orElseThrow(new BusinessException("参数无记录"));
    }

    @GetMapping("/getDecimal/{id}")
    public BigDecimal getDecimal(@PathVariable String id) {
        return sysConfigService.getBigDecimal(id);
    }

    @PostMapping("/del/{id}")
    public void del(@PathVariable String id) {
        sysConfigRepo.deleteById(id);
    }

    @PostMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, @RequestBody PageQuery pageQuery) throws IOException {
        List<SysConfig> data = all(pageQuery).getContent();
        ExcelUtils.export(response, data);
    }
}

